package com.lilihub.miaosha.config;

import com.lilihub.miaosha.domain.MiaoshaUser;
import com.lilihub.miaosha.intercepter.UserContext;
import com.lilihub.miaosha.service.MiaoshaUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @BelongsProject: miaosha2
 * @BelongsPackage: com.lilihub.miaosha.config
 * @Author: LiYing
 * @CreateTime: 2021-04-26 16:38
 * @Description:
 */
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private MiaoshaUserService userService;

    //如果存在MiaoshaUser对象，则直接返回
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {

        Class<?> parameterType = methodParameter.getParameterType();

        return parameterType == MiaoshaUser.class;
    }


    //如果不存在MiaoshaUser对象，则对其进行获取
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {


        /*
        //此段代码已经配置在拦截器中
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

        String paramToken = request.getParameter(MiaoshaUserService.COOKI_NAME_TOKEN);
        String cookieToken = getCookieValue(request,MiaoshaUserService.COOKI_NAME_TOKEN);

        if (StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)){
            return null;
        }
        String token = StringUtils.isEmpty(paramToken) ? cookieToken : paramToken;
        MiaoshaUser user = userService.getbyToken(token,response);

        return user;
        */

        /**
         * 直接从当前线程从取到user对象
         * AccessInterceptor中已经将user对象保存在了UserContext中
         */
        return UserContext.getUser();


    }

    private String getCookieValue(HttpServletRequest request, String cookiNameToken) {

        Cookie[] cookies = request.getCookies();

        if (cookies == null || cookies.length <=0){
            return null;
        }

        for (Cookie c : cookies){
            if (c.getName().equals(cookiNameToken)){
                return c.getValue();
            }
        }
        return null;
    }
}
